package com.xiaowen.controller;

import com.xiaowen.entity.User;
import com.xiaowen.service.UserService;
import com.xiaowen.util.CorrectJsonObject;
import com.xiaowen.util.ErrorJsonObject;
import com.xiaowen.util.emailCode.EmailManage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * Created by 15c on 2017/11/16.
 */
@Controller
@RequestMapping("/users")
public class UserController {
    @Autowired
    UserService userService;

    /**
     * 获取验证码
     *
     * @param email 邮箱
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getVerificationCode", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String getVerificationCode(@RequestParam(required = false) String email) {
        //前端判断email格式以及不允许传空值
        //发送验证码到邮箱
        EmailManage emailManage = new EmailManage(email);
        emailManage.addEmail();
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("生成发送验证码成功");
        correctJsonObject.setData(0);
        return correctJsonObject.toString();
    }

    /**
     * 邮箱注册
     *
     * @param email
     * @param password
     * @param verificationCode
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register/email", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String registerByEmail(@RequestParam(required = false) String email,
                           @RequestParam(required = false) String password,
                           @RequestParam(required = false) String verificationCode) {

        //前端判断email格式以及不允许传空值以及验证码、密码不能传空值
        //发送验证码到邮箱
        //获得当前邮箱信息
        ErrorJsonObject errorJsonObject;
        String checkCode = null;
        //此处可能会出现空指针异常，在用户没获取验证码是会出现
        try {
            checkCode = EmailManage.getEmail(email).getMailCheckString();
        } catch (NullPointerException e) {
            errorJsonObject = new ErrorJsonObject(101, "用户未获取验证码！");
            return errorJsonObject.toJSONString();
        }
//        if(checkCode==null || checkCode.equals("")) {
//             errorJsonObject = new ErrorJsonObject(101, "用户未获取验证码！");
//            return errorJsonObject.toJSONString();
//        }
        if (!checkCode.equals(verificationCode)) {
            errorJsonObject = new ErrorJsonObject(102, "验证码不匹配！");
            return errorJsonObject.toJSONString();
        }
        User user = new User();
        user.setUserPassword(password);
        user.setUserEmail(email);
        if (null != userService.showUser(user)) {
            errorJsonObject = new ErrorJsonObject(103, "用户已注册！");
            return errorJsonObject.toJSONString();
        }
       int result= userService.addUserByEmail(user);
        if(result==1){
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("注册成功");
            correctJsonObject.setData(userService.showUser(user));
            return correctJsonObject.toString();
        }else {
            errorJsonObject = new ErrorJsonObject(104, "注册失败，请重试！");
            return errorJsonObject.toJSONString();
        }

    }

    /**
     * 用户通过手机号注册
     *
     * @param telnumber        电话号码
     * @param password         密码
     * @param verificationCode 验证码
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/register/tel", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String registerByTelPhone(@RequestParam(required = false) String telnumber,
                              @RequestParam(required = false) String password,
                              @RequestParam(required = false) String verificationCode) {
        //前端判断telnumber格式以及不允许传空值以及验证码、密码不能传空值
        ErrorJsonObject errorJsonObject;
        User user = new User();
        user.setUserPassword(password);
        user.setUserPhone(telnumber);
        if (null != userService.showUserByPhone(user)) {
            errorJsonObject = new ErrorJsonObject(103, "用户已注册！");
            return errorJsonObject.toJSONString();
        }
        userService.addUserByPhone(user);
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("注册成功");
        correctJsonObject.setData(0);
        return correctJsonObject.toString();

    }

    /**
     * 邮箱登录
     *
     * @param email
     * @param password
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/login", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String login(@RequestParam(required = false) String email,
                 @RequestParam(required = false) String password) {
        //前端判断参数不能为空
        ErrorJsonObject errorJsonObject;
        System.out.println("email:"+email+" password:"+password);
        User user = userService.login(email);

        if (null == user || !user.getUserPassword().equals(password)) {

            errorJsonObject = new ErrorJsonObject(104, "用户名或密码错误！");
            return errorJsonObject.toJSONString();
        }
        System.out.println("userpassword"+user.getUserPassword());
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("登录成功！");
        correctJsonObject.setData(user);
        return correctJsonObject.toString();
    }

    /**
     * 用于用户修改自己的信息
     *
     * @param user user对象其中需要包含userId。
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/details/revise", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    String userReviseInfo(@RequestBody(required = false) User user) {
        ErrorJsonObject errorJsonObject;
        int i = 0;
        try {
            i = userService.updateUser(user);
        } catch (Exception e) {
            errorJsonObject = new ErrorJsonObject(105, "更新错误！");
            return errorJsonObject.toJSONString();
        }
        if (i != 1) {
            errorJsonObject = new ErrorJsonObject(105, "更新错误！");
            return errorJsonObject.toJSONString();
        }
        CorrectJsonObject correctJsonObject = new CorrectJsonObject("更新成功！");
        correctJsonObject.setData(0);
        return correctJsonObject.toString();

    }

    /**
     * 用于展示用户的基本信息(可用于查询他人也可用于查询自己)
     *
     * @param userId userId
     * @return resultUser的json数据
     */
    @ResponseBody
    @RequestMapping(value = "/details/show", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    String userShowInfo(@RequestParam(required = false) Integer userId) {
        ErrorJsonObject errorJsonObject;
        User user;
        user = userService.selectUserPartInfoByUserId(userId);
        if (null == user) {
            errorJsonObject = new ErrorJsonObject(106, "信息查询出错！");
            return errorJsonObject.toJSONString();
        }

        CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功！");
        correctJsonObject.setData(user);
        return correctJsonObject.toString();
    }

    /**
     * 用户图片上传入口
     *
     * @param request 用户请求
     * @param image   图片
     * @return 结果json
     */
    @ResponseBody
    @RequestMapping(value = "/details/image-upload", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    public String imageUpload(HttpServletRequest request,@RequestParam(required = false) String image) {
        System.out.println("image为：" + image + " end");
        ErrorJsonObject errorJsonObject;
        //指定头类型
        String headerPng = "data:image/png;base64,";
        String headerJpG = "data:image/jpeg;base64,";

        //获取服务器的路径
        String realPath = request.getSession().getServletContext().getRealPath("/resources/img");

        System.out.println("realPath为：" + realPath + "  end");
        //声明图片地址
        String imgAddress = null;
        //获取扩展名
        String extensionName = ".png";
        System.out.println("--------------->" + extensionName);
        if (image != null && (image.indexOf(headerPng) != 0 || image.indexOf(headerJpG) != 0)) {
            String headPng = image.substring(0, headerPng.length());
            String headJpG = image.substring(0, headerJpG.length());
            if (headerJpG.equals(headJpG)) {
                //去掉头部
                image = image.substring(headerJpG.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else if (headerPng.equals(headPng)) {
                //去掉头部
                image = image.substring(headerPng.length());
                BASE64Decoder decoder = new BASE64Decoder();
                try {
                    if (!image.isEmpty()) {

                        //以当前时间加随机数命名上传文件
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmssSSS");
                        String date = sdf.format(new java.util.Date());


                        //设置图片名为当前时间加随机数
                        imgAddress = date + new Random().nextInt() + extensionName;

                        //将文件上传到服务器
                        byte[] decodedBytes = decoder.decodeBuffer(image);

                        FileOutputStream out = new FileOutputStream(realPath + "/" + imgAddress);

                        out.write(decodedBytes);

                        out.close();

                        CorrectJsonObject correctJsonObject = new CorrectJsonObject("上传成功！");
                        correctJsonObject.setData(imgAddress);
                        return correctJsonObject.toString();

                    } else {

                        errorJsonObject = new ErrorJsonObject(108, "上传的文件不存在！");
                        return errorJsonObject.toJSONString();

                    }
                } catch (IOException e) {

                    errorJsonObject = new ErrorJsonObject(108, e.getMessage());
                    return errorJsonObject.toJSONString();

                }
            } else {
                errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
                return errorJsonObject.toJSONString();
            }
        } else {
            errorJsonObject = new ErrorJsonObject(107, "文件不存在或格式不正确");
            return errorJsonObject.toJSONString();
        }
    }
}

